package com.icinema.main;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.icinema.client.ICinema;
import com.icinema.client.UserService;
import com.icinema.client.UserServiceAsync;
import com.icinema.vo.User;

public class LoginView extends Composite {
	TextBox txtEmail = new TextBox();
	PasswordTextBox txtPassword = new PasswordTextBox();
	ICinema iCinema;
	private final UserServiceAsync userService = GWT
	.create(UserService.class);	
	public void setICinema(ICinema c){
		iCinema = c;
	}
	private void initUser(){
		User user = new User();
		user.setEmail("zawhtutwin@gmail.com");
		user.setPassword("admin");
		user.setStatus("A");
		userService.addUser(user,new AsyncCallback<String>(){

			@Override
			public void onFailure(Throwable caught) {
				
			}

			@Override
			public void onSuccess(String result) {
				
			}
			
		});
	}
	@SuppressWarnings("deprecation")
	public LoginView(){
		initUser();
		FlexTable formTable = new FlexTable();
		initWidget(formTable);
		formTable.setText(0,0,"Email");
		formTable.setWidget(0,1,txtEmail);
		formTable.setText(1,0,"Password");
		formTable.setWidget(1,1,txtPassword);
		Button btnLogin = new Button("Login");
		formTable.setWidget(2,1, btnLogin);
		Hyperlink backLink = new Hyperlink();
		backLink.setText("Back");
		backLink.setStyleName("hyper-link");
		formTable.setWidget(3,1,backLink);
		btnLogin.addMouseDownHandler(new MouseDownHandler(){
			@Override
			public void onMouseDown(MouseDownEvent event) {
				final User filter = new User();
				filter.setEmail(txtEmail.getText());
				filter.setPassword(txtPassword.getText());
				userService.getUser(filter, new AsyncCallback<User>(){
					@Override
					public void onFailure(Throwable caught) {
						
						
					}
					@Override
					public void onSuccess(User result) {
							if(result!=null){
								if(filter.getEmail().equals("zawhtutwin@gmail.com")){
									iCinema.showAdminPanelCallBack();
								}else{
									iCinema.showUserPanelCallBack();
								}
							}
							iCinema.validLoginCallBack(result);
					}
					
				});
			}
			
		});
		backLink.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				iCinema.showHomeViewCallBack();
			}
		});
		
	}
}